package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Banner;
import cn.wolfcode.wolf2w.query.BannerQuery;
import cn.wolfcode.wolf2w.repository.BannerRepository;
import cn.wolfcode.wolf2w.service.IBannerService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
public class BannerServiceImpl implements IBannerService {

    @Autowired
    private BannerRepository bannerRepository;
    @Autowired
    private MongoTemplate template;
    
    @Autowired
    private  IBannerService bannerService;



    @Override
    public void save(Banner banner) {
        banner.setId(null);
        bannerRepository.save(banner);
    }

    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public Banner get(String id) {
        return bannerRepository.findById(id).orElse(null);
    }

    @Override
    public List<Banner> list() {
        return bannerRepository.findAll();
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {

        //查询对象
        Query query = new Query();

        //查询总数

        Pageable pageable =PageRequest.of(qo.getCurrentPage()-1,
                qo.getPageSize(),Sort.Direction.ASC,"_id");

        return DBHelper.query(template, Banner.class, query, pageable);
    }

    @Override
    public void saveOrUpdate(Banner banner) {
        //判断是否带id
        if (StringUtils.hasLength(banner.getId())){
            //有则编辑
            this.update(banner);
        }else {
            //无则添加
            this.save(banner);
        }
    }

    @Override
    public List<Banner> queryBanner(int type) {

        Pageable pageable =PageRequest.of(0,5,Sort.Direction.ASC,"sequence");

        return bannerRepository.findByStateAndType(Banner.STATE_NORMAL,type,pageable);
    }
}
